<template>
  <div>
    <!-- 面包靴导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>新增商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="商品参数"></el-step>
        <el-step title="基本信息"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--侧边tab栏 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-tabs
          tab-position="top"
          label-position="top"
          v-model="activeIndex"
          :before-leave="beforeTableave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat"> </el-form-item>

            <!-- jilian -->
            <el-cascader
              v-model="addForm.goods_cat"
              :options="cateList"
              clearable
              :props="{
                expandTrigger: 'hover',

                label: 'cat_name',
                value: 'cat_id',
              }"
              @change="handleCascaderChange"
            ></el-cascader>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  :label="item2"
                  border
                  v-for="(item2, index2) in item.attr_vals"
                  :key="index2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 图片上传 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片桑川 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 富文本 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              size="small"
              style="margin-top: 15px"
              @click="onSubmit"
              >提交!</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- dianji 点击现实对话框 -->
    <el-dialog title="预览图片" :visible.sync="dialogVisible" width="30%">
      <img :src="preview" alt="" width="100%" height="100%" />
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'

export default {
  data () {
    return {
      activeIndex: 0,
      tabPosition: 'right',
      addForm: {
        goods_introduce: '',
        goods_name: '', // 商品名称
        goods_price: 0, // 价格
        goods_number: 0, // 数量
        goods_weight: 0, // 重量
        goods_cat: '', // 分类
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ], // 商品名称
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ], // 价格
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ], // 数量
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ], // 重量
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ] // 分类
      },
      cateList: [],
      // 动态参数
      manyTableData: [],
      // 静态属
      onlyTableData: [],
      // 手动设置请求头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      dialogVisible: false,
      preview: ''
    }
  },
  created () {
    this.getCateList()
    // ct==todo测试语句
    this.activeIndex = '2'
    this.addForm.goods_cat = [1, 3, 6]
    this.handleTabClick()
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  },
  methods: {
    // 上传验证
    onSubmit () {
      this.$refs.addFormRef.validate(async (isOk) => {
        if (isOk === false) return this.$message.error('验证失败！请重新填写必填项！')
        this.$message.success('验证成功！')

        const newFrom = cloneDeep(this.addForm)
        newFrom.goods_cat = newFrom.goods_cat.join(',')

        this.manyTableData.forEach(ele => {
          newFrom.attrs.push({
            attr_id: ele.attr_id,
            attr_value: ele.attr_vals.join(' ')
          })
        })
        this.onlyTableData.forEach(ele => {
          newFrom.attrs.push({
            attr_id: ele.attr_id,
            attr_value: ele.attr_vals
          })
        })
        // console.log(newFrom)
        const { data: res } = await this.$http.post('goods', newFrom)
        if (res.meta.status !== 201) return this.$message.error('提交失败!')
        this.$message.success('提交成功!')
        this.$router.push('/goods')
      })
    },
    // 文件上传成功后的狗子
    handleSuccess (res) {
      this.addForm.pics.push({
        pic: res.data.tmp_path

      }
      )
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (res) {
      this.preview = res.response.data.url
      this.dialogVisible = true
    },
    // 文件列表移除文件时的钩子
    handleRemove (res) {
      const tmpPath = res.response.data.tmp_path
      this.addForm.pics = this.addForm.pics.filter(ele => {
        return ele.pic !== tmpPath
      })
    },
    async handleTabClick () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        console.log(res.data)

        res.data.forEach(ele => {
          ele.attr_vals = ele.attr_vals.length === 0 ? [] : ele.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params:
         {
           sel: 'only'
         }
        })
        this.onlyTableData = res.data
      }
    },
    beforeTableave (activeName, oldActiveName) {
      console.log(activeName, oldActiveName)
      if (activeName !== '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择分类！')
        return false
      }
    },
    handleCascaderChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm = []
      }
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
</style>
